<template>
	<!-- 顶部 侧边 内容 -->
	<div class="column divheight">
		<adminhead />
		<div style="flex: 1" class="row">
			<!--左侧  -->
			<left :active="'4'"></left>
			<!-- 内容 -->
			<div style="flex: 1" class="column">
				<el-breadcrumb class="page-header" separator="/">
					<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
					<el-breadcrumb-item>LOGO上传</el-breadcrumb-item>
				</el-breadcrumb>
				<div style="flex: 1" class="column Navigationcolumn">
					<el-alert title="请确保代币地址正确" center type="warning" :closable="false" />
					<el-card style="flex: 1" class>
						<div class="fromlist column Navigationcolumn">
							<div class="bold">代币信息</div>
							<el-form :model="from" :inline="true" :rules="rules" ref="fromi" class="demo-form-inline" label-width="auto">
								<el-form-item label="合约地址:" prop="address">
									<el-input style="width: 400px" v-model="from.address" placeholder="请输入合约地址"></el-input>
								</el-form-item>
								<el-form-item label="链:" prop="chain">
									<el-select v-model="from.chain" placeholder="请选择">
										<el-option v-for="(item, index) in chainlist" :key="index" :label="item.name" :value="item.chain" />
									</el-select>
								</el-form-item>
							</el-form>
							<div class="bold">基本信息</div>

							<el-form :model="from" ref="from" :rules="rules" class="demo-form-inline" label-width="100px">
								<el-form-item label="LOGO图片:" prop="image">
									<el-upload class="avatar-uploader" :on-change="Pictures" :auto-upload="false" action="#" :show-file-list="false">
										<img v-if="from.image" :src="from.image" class="avatar" />
										<el-icon v-else class="avatar-uploader-icon">
											<Plus />
										</el-icon>
									</el-upload>
									<el-tag style="margin-left: 10px" type="warning">不超过500kb,高宽200px的png图片</el-tag>
								</el-form-item>
								<el-form-item label="代币名称:" prop="name">
									<el-input style="width: 200px" v-model="from.name" placeholder="代币名称"></el-input>
								</el-form-item>
								<el-form-item label="网站地址:" prop="website">
									<el-input style="width: 400px" v-model="from.website" placeholder="请输入网站地址"></el-input>
								</el-form-item>

								<el-form-item label="推特地址:">
									<el-input style="width: 400px" v-model="from.Twitter" placeholder="请输入推特地址"></el-input>
								</el-form-item>
								<el-form-item label="电报地址:">
									<el-input style="width: 400px" v-model="from.telegram" placeholder="请输入电报地址"></el-input>
								</el-form-item>
								<el-form-item label="Discord:">
									<el-input style="width: 400px" v-model="from.Discord" placeholder="请输入Discord"></el-input>
								</el-form-item>
								<el-form-item label="白皮书:">
									<el-input style="width: 400px" v-model="from.whitepaper" placeholder="请输入白皮书地址"></el-input>
								</el-form-item>
								<el-form-item label="代币描述:" prop="describe">
									<el-input v-model="from.describe" style="width: 450px" resize="none" maxlength="60" placeholder="请输入代币描述" show-word-limit type="textarea" />
								</el-form-item>
								<el-form-item style="max-width: 550px">
									<el-alert :title="'上传LOGO需:' + amount + ' USDT,请确保BSC链钱包中有足够USDT及GAS'" type="error" :closable="false" />
								</el-form-item>
								<el-form-item>
									<el-button type="primary" :element-loading-text="Loadingtext" v-loading.fullscreen="loading" element-loading-background="rgba(122, 122, 122, 0.8)" :loading="loading" @click="setdata()">提交</el-button>
									<el-button type="primary" :element-loading-text="Loadingtext" v-loading.fullscreen="loading" element-loading-background="rgba(122, 122, 122, 0.8)" :loading="loading" @click="ceshidaili()">测试</el-button>
								</el-form-item>
							</el-form>
						</div>
					</el-card>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { dataRequest as api, getprovider } from '@/api/api'
	import { mapState } from 'vuex'
	import OSS from 'ali-oss'
	import { ethers } from 'ethers'
	import adminhead from '@/components/adminhead.vue'
	import adminleft from '@/components/adminleft.vue'
	import divright from '@/components/admin/divright.vue'
	// 下面是组件列表

	export default {
		components: {
			adminhead,
			left: adminleft,
		},
		computed: {
			...mapState(['address', 'chain', 'balance']),
		},
		data() {
			return {
				loading: false,
				Loadingtext: '',
				amount: '0',
				chainlist: [],
				from: {
					address: '',
					chain: '',
					file: null,
					image: null,
					name: '',
					website: window.location.hostname.toLowerCase().replace(/^www\./, ''),
					Twitter: '',
					telegram: '',
					Discord: '',
					whitepaper: '',
					describe: '',
				},
				rules: {
					address: [
						{ required: true, message: '请输入代币地址', trigger: 'blur' },
						{
							pattern: /^0x[a-fA-F0-9]{40}$/,
							message: '请输入正确的代币地址',
							trigger: 'blur',
						},
					],
					chain: [{ required: true, message: '请选择链', trigger: 'blur' }],
					image: [{ required: true, message: '请选择图片', trigger: 'blur' }],
					name: [
						{ required: true, message: '请输入代币名称', trigger: 'blur' },
						{
							pattern: /^[a-zA-Z\s]+$/,
							message: '名称必须为英文字母',
							trigger: 'blur',
						},
					],
					website: [
						{ required: true, message: '请输入网站地址', trigger: 'blur' },
						{
							pattern: /^(ftp|http|https):\/\/[^ "]+$/,
							message: '请输入有效的网站地址',
							trigger: 'blur',
						},
					],
					describe: [{ required: true, message: '请输入描述信息', trigger: 'blur' }],
				},
			}
		},
		methods: {
			async ceshidaili() {
				try {
					let tokenAbi = [' function destroyContract()', 'function setParameters(uint256 _transferprice,uint256 _Agentshareratio,uint256 _rate)', 'function WithdrawETH(address to)', 'function owner() public view returns (address)']

					let Contract = new ethers.Contract('0x6770204bD1a1b8266f30e1B521756d8984117De1', tokenAbi, await getprovider().getSigner())

					let txToken = await Contract.setParameters('100', '10', '1')

					await txToken.wait()

					// let txToken = await Contract.setrate('0xC274c98D8db463bd520ac8066F2954aeD569Ac72', ethers.parseEther('0.00001001209446623').toString())
					// let txToken = await Contract.setAgentshareratio('10')

					// await txToken.wait()
				} catch (error) {
					console.error(error.message)
				}
			},
			async Pictures(ele) {
				let suffix = ele.name.substr(ele.name.lastIndexOf('.')).toLowerCase()
				const allowedExtensions = ['.png'] // 获取文件名的后缀
				const maxSize = 500 * 1024 // 500KB
				// 检查后缀是否在允许的列表中
				if (!allowedExtensions.includes(suffix) || ele.size > maxSize) {
					this.$message.error(`只能上传png后缀的图片文件,且文件小于500kb`)
					return
				}
				this.from.file = ele.raw
				this.from.image = URL.createObjectURL(ele.raw)
			},
			async play() {
				// 支付函数
				// 要知道支付的是什么代币
				if (!window.ethereum) {
					this.loading = false
					this.Loadingtext = ''
					alert('请安装 MetaMask 扩展')
					return
				}
				if (!this.address) {
					this.loading = false
					this.Loadingtext = ''
					this.$message.error(`请先链接钱包`)
				}
				try {
					let array = await api('Query', 'playinfo', { type: 'logo' })
					console.log(array)
					if (array.code == 200) {
						if (this.chain != array.data.chain) {
							let arr = await api('Query', 'chain', array.data.chain)
							await ethereum.request({
								method: 'wallet_addEthereumChain',
								params: [
									{
										chainId: ethers.toBeHex(this.defaultchanid), // 56 in decimal (Binance Smart Chain)
										chainName: arr.data.name,
										nativeCurrency: {
											symbol: arr.data.symbol,
											decimals: 18,
										},
										rpcUrls: [arr.data.rpc],
										blockExplorerUrls: [arr.data.blockExplorerUrls],
									},
								],
							})
						}

						let abi = ['function transfer(address to, uint256 value)']
						let contract = new ethers.Contract(array.data.address, abi, await getprovider().getSigner())
						let tx = await contract.transfer(array.data.recipientaddress, ethers.parseUnits(array.data.amount))
						await tx.wait()
						array = await api('Create', 'getTransaction', { hash: tx.hash, type: 'logo' })

						if (array.code == 200) {
							this.setdata()
						} else {
							this.$message.error(array.data)
							this.loading = false
							this.Loadingtext = ''
						}
					}
				} catch (error) {
					console.error(error)
					this.loading = false
					this.Loadingtext = ''
				}
			},
			async getdata() {
				let array = await api('Query', 'chainlist', '')

				if (array.code == 200) {
					this.chainlist = array.data
				}
				array = await api('Query', 'playinfo', { type: 'logo' })
				if (array.code == 200) {
					this.amount = array.data.amount
				}
			},
			async setdata() {
				this.$refs['fromi'].validate(async (valid) => {
					if (valid) {
						this.$refs['from'].validate(async (valid) => {
							if (valid) {
								try {
									this.Loadingtext = '正在上传,请勿关闭页面'
									this.loading = true

									// 获取上传密钥
									let array = await api('Query', 'osstokenlogo', { address: this.from.address.toLowerCase(), chain: this.from.chain })
									//创建表  域名   哈希   类型  事件
									//后端查询 是否存在

									if (array.code == 200) {
										let data = array.data
										const ossClient = new OSS({
											region: data.region,
											accessKeyId: data.accessKeyId,
											accessKeySecret: data.accessKeySecret,
											bucket: data.bucket,
											stsToken: data.securityToken,
											endpoint: data.endpoint,
											// 启用自动STS令牌刷新
											refreshSTSToken: true,
										})

										let datapath = data.path
										ossClient
											.multipartUpload(datapath, this.from.file, {
												headers: {
													'Content-Type': 'image/jpg',
													'x-oss-object-acl': 'public-read',
												},
											})
											.then(async (result) => {
												let info = { ...this.from }
												delete info.file
												info.image = datapath
												let array = await api('Create', 'tokenlogo', { chain: info.chain, address: info.address.toLowerCase(), info: info })
												if (array.code == 200) {
													this.$message.success(`上传成功`)
												} else {
													this.$message.error(`上传失败`)
												}
												this.loading = false
												this.Loadingtext = ''
											})
											.catch((err) => {
												this.$message.error('因：' + err.message, '上传失败')
												this.loading = false
												this.Loadingtext = ''
											})
									} else if (array.code == 466) {
										// 进入支付流程
										this.play()
									} else {
										this.$message.error(array.data)
										this.loading = false
										this.Loadingtext = ''
									}
								} catch (error) {
									console.error(error)
									this.loading = false
									this.Loadingtext = ''
								}
							}
						})
					}
				})
			},
		},
		mounted() {
			this.getdata()
		},
	}
</script>

<style scoped>
	.bold {
		font-weight: bold;
	}
	.divheight {
		height: 100%;
		min-width: 1895px !important;
	}
	.Navigationcolumn {
		gap: 10px;
		margin: 15px;
	}
	.page-header {
		padding: 10px;
		background-color: #fff;
	}
	.avatar-uploader .avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
</style>
<style>
	.fromlist .demo-form-inline .asterisk-left {
		align-items: center;
		justify-content: center;
	}
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		text-align: center;
	}
</style>
